//
//  AppLoadingViewController.m
//  BosidengIphone
//
//  Created by  on 11-12-25.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "AppLoadingViewController.h"
#import "AppDelegate.h"
#import "ASINetworkQueue.h"
#import "ASIHTTPRequest.h"
#import "NewsItemsXmlParser.h"
#import "SyncRequestParseOperation.h"
#import "NewsData.h"
#import "VideoItemsXmlParser.h"
#import "VideoData.h"
#import "BrandItemsXmlParser.h"
#import "BrandData.h"
#import "StoreItemsXmlParser.h"
#import "StoreData.h"
#import "CityItemsXmlParser.h"
#import "CityData.h"
#import "ProductItemsXmlParser.h"
#import "ProductData.h"
#import "MyShowItemsXmlParser.h"
#import "MyShowData.h"

static int BUFFER_IMAGE_COUNT = 0;

@implementation AppLoadingViewController
@synthesize progressView;
@synthesize backImageView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        requestCount = BUFFER_IMAGE_COUNT;
        finishedCount = 0;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc {
    [backImageView release];
    [progressView release];
    [super dealloc];
}

#pragma mark - View lifecycle
- (void)updateProgressView {
    float progress = (float)finishedCount / requestCount;
    //NSLog(@"time:%.1f", progress);
    [progressView setProgress:(progress)];
    if (progress > 0.99) {
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(loadMainView) userInfo:nil repeats:NO];
    }
}

- (void)addRequest:(NSString *)url andKey:(NSString *)key andXmlParser:(ItemsXmlParser *)parser {
    SyncRequestParseOperation *operation = [[SyncRequestParseOperation alloc] initWithURLString:url xmlParser:parser delegate:self];
    [operation setUserInfo:[self setRequestName:key]];
    [requestQueue addOperation:operation];
    [operation release];
    
    requestCount++;
}

- (void)addFileRequest:(NSString *)url {
    NSString *path = [AppDelegate getCacheFilePathByUrl:url];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    [request setDownloadDestinationPath:path];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(fileRequestComplete:)];
    [request setDidFailSelector:@selector(requestFailed:)];
    [requestQueue addOperation:request];
    requestCount++;
}

- (void)fileRequestComplete:(ASIHTTPRequest *)request {
    finishedCount++;
    [self updateProgressView];
}

- (void)addBackgroundRequest:(NSString *)url {
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(backgroundRequestComplete:)];
    [request setDidFailSelector:@selector(requestFailed:)];
    [requestQueue addOperation:request];
    requestCount++;
}

- (void)backgroundRequestComplete:(ASIHTTPRequest *)request {
    NSString *imageUrl = [request responseString];
    NSLog(@"request back image url:%@", imageUrl);
    if (imageUrl == nil || [@"" isEqualToString:imageUrl]) {
        finishedCount++;
        [self updateProgressView];
        return;
    }
    NSString *path = [AppDelegate getCacheFilePathByUrl:imageUrl];
    request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imageUrl]];
    [request setDownloadDestinationPath:path];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(backImageRequestComplete:)];
    [request setDidFailSelector:@selector(requestFailed:)];
    [requestQueue addOperation:request];
}

- (void)backImageRequestComplete:(ASIHTTPRequest *)request {
    finishedCount++;
    [self updateProgressView];
    NSString *path = [request downloadDestinationPath];
    NSString *oldPath = [AppDelegate getBackImagePath];
    if (![@"" isEqualToString:oldPath] && ![oldPath isEqualToString:path]) {
        [AppDelegate deleteFile:oldPath];
    }
    [AppDelegate setBackImagePath:path];
}

- (void)parseXml {
    NSString *url = [NSString stringWithFormat:@"%@/getproducts.ashx?Lan=%@", [AppDelegate serviceUrl], [AppDelegate getLanguage]];
    ProductItemsXmlParser *productParser = [[ProductItemsXmlParser alloc] init];
    [self addRequest:url andKey:@"ProductList" andXmlParser:productParser];
    [productParser release];
    NSLog(@"request ProductList url = %@", url);
    
    url = [NSString stringWithFormat:@"%@/GetNews.ashx?lan=%@", [AppDelegate serviceUrl], [AppDelegate getLanguage]];
    NewsItemsXmlParser *newsParser = [[NewsItemsXmlParser alloc] init];
    [self addRequest:url andKey:@"NewsList" andXmlParser:newsParser];
    [newsParser release];
    NSLog(@"request NewsList url = %@", url);
    
    url = [NSString stringWithFormat:@"%@/Getvideo.ashx?lan=%@&type=iphone", [AppDelegate serviceUrl], [AppDelegate getLanguage]];
    
    VideoItemsXmlParser *videoParser = [[VideoItemsXmlParser alloc] init];
    [self addRequest:url andKey:@"VideoList" andXmlParser:videoParser];
    [videoParser release];
    NSLog(@"request VideoList url = %@", url);
    
    url = [NSString stringWithFormat:@"%@/Getbrand.ashx?lan=%@", [AppDelegate serviceUrl], [AppDelegate getLanguage]];
    
    BrandItemsXmlParser *brandParser = [[BrandItemsXmlParser alloc] init];
    [self addRequest:url andKey:@"BrandList" andXmlParser:brandParser];
    [brandParser release];
    NSLog(@"request BrandList url = %@", url);
    
    url = [NSString stringWithFormat:@"%@/getStore.ashx?lan=%@", [AppDelegate serviceUrl], [AppDelegate getLanguage]];
    
    StoreItemsXmlParser *storeParser = [[StoreItemsXmlParser alloc] init];
    [self addRequest:url andKey:@"StoreList" andXmlParser:storeParser];
    [storeParser release];
    NSLog(@"request StoreList url = %@", url);
    
    url = [NSString stringWithFormat:@"%@/getCity.ashx?lan=%@", [AppDelegate serviceUrl], [AppDelegate getLanguage]];
    
    CityItemsXmlParser *cityParser = [[CityItemsXmlParser alloc] init];
    [self addRequest:url andKey:@"CityList" andXmlParser:cityParser];
    [cityParser release];
    NSLog(@"request CityList url = %@", url);
    
    url = [NSString stringWithFormat:@"%@/GetAllShow.ashx", [AppDelegate serviceUrl]];
    MyShowItemsXmlParser *showParser = [[MyShowItemsXmlParser alloc] init];
    [self addRequest:url andKey:@"AllShowList" andXmlParser:showParser];
    [showParser release];
    NSLog(@"request AllShowList url = %@", url);
    
    url = [NSString stringWithFormat:@"%@/GetBackground.ashx?type=4", [AppDelegate serviceUrl]];
    [self addBackgroundRequest:url];
    NSLog(@"request Background Image url = %@", url);
    
    url = [NSString stringWithFormat:@"%@/language/language_%@.xml", [AppDelegate serviceUrl], [AppDelegate getLanguage]];
    [self addFileRequest:url];
    NSLog(@"request language config url = %@", url);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [progressView setProgress:0];
    NSString *path = [AppDelegate getBackImagePath];
    if (path == nil || [@"" isEqualToString:path]) {
        //backImageView.image = [UIImage imageNamed:@"LoaddingBackground.jpg"];
    } else {
        backImageView.image = [UIImage imageWithContentsOfFile:path];
    }
    [AppDelegate cleanLanguageStringBuffer];
    [self parseXml];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)loadMainView {
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    [delegate showIndexView];
}

#pragma mark - request delegate

- (void)requestBufferImage:(NSString *)url {
    NSLog(@"Request Image! URL=%@", url);
    NSString *path = [self getLocalImagePath:url];
    if ([AppDelegate checkFileExist:path]) {
        NSLog(@"file exist! path=%@", path);
        finishedCount++;
        [self updateProgressView];
        return;  
    }
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    [request setDownloadDestinationPath:path];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestComplete:)];
    [request setDidFailSelector:@selector(requestFailed:)];
    [requestQueue addOperation:request];
}

- (void)requestComplete:(ASIHTTPRequest *)request {
    finishedCount++;
    [self updateProgressView];
    NSLog(@"Image Request success! path=%@", [request downloadDestinationPath]);
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    finishedCount++;
    [self updateProgressView];
    NSLog(@"Image Request Failed! path=%@", [request downloadDestinationPath]);
}

- (void) updateLocalNewsList:(NSArray *)serviceData {
    for (int i = 0; i < [serviceData count]; i++) {
        NSDictionary *data = [serviceData objectAtIndex:i];
        NSString *infoId = [data objectForKey:@"InfoID"];
        NewsData *localData = [NewsData getItemByID:infoId];
        if (localData == nil) {
            localData = [[[NewsData alloc] init] autorelease];
        } else {
            //判断是否需要删除本地图片
            NSString *localUrl = localData.iPhoneSLImg;
            NSString *serviceUrl = [data objectForKey:@"iPhoneSLImg"];
            if (![self checkImageUrlIsSame:localUrl serviceUrl:serviceUrl]) {
                [localData removeSmallImage];
            }
            
            NSString *allImages = localData.newsImgs;
            NSString *serviceAllImages = [data objectForKey:@"NewsImgs"];
            if (![allImages isEqualToString:serviceAllImages]) {
                [localData removeNewsImages];
            }
        }
        //添加，更新最新的数据
        [localData setValue:data];
        [localData save];
        //NSLog(@"save new data(%@)", localData);
    }
    //取得最新的数据集
    NSArray *localDatas = [NewsData getAllItems];
    for (NewsData *data in localDatas) {
        NSString *localId = data.infoID;
        if ([self isNeedDeleteItem:localId serviceData:serviceData serviceKey:@"InfoID"]) {
            //NSLog(@"delete not exist data(%@)", data);
            [data removeLocalImages];
            [data deleteObject];
        }
    }
}

- (void) updateLocalVideoList:(NSArray *)serviceData {
    for (int i = 0; i < [serviceData count]; i++) {
        NSDictionary *data = [serviceData objectAtIndex:i];
        NSString *uid = [data objectForKey:@"VideoID"];
        VideoData *localData = [VideoData getItemByID:uid];
        if (localData == nil) {
            localData = [[[VideoData alloc] init] autorelease];
        } else {
            //判断是否需要删除本地图片
            NSString *localUrl = localData.image;
            NSString *serviceUrl = [data objectForKey:@"Image"];
            if (![self checkImageUrlIsSame:localUrl serviceUrl:serviceUrl]) {
                [AppDelegate deleteFile:[self getLocalImagePath:localUrl]];
            }
        }
        //NSLog(@"save new data(%@)", localData);
        //添加，更新最新的数据
        [localData setValue:data];
        [localData save];
    }
    //取得最新的数据集
    NSArray *localDatas = [VideoData getAllItems];
    for (VideoData *data in localDatas) {
        NSString *localId = data.videoID;
        if ([self isNeedDeleteItem:localId serviceData:serviceData serviceKey:@"VideoID"]) {
            //NSLog(@"delete not exist data(%@)", data);
            [data removeLocalImages];
            [data deleteObject];
        }
    }
}

- (void) updateLocalBrandList:(NSArray *)serviceData {
    for (int i = 0; i < [serviceData count]; i++) {
        NSDictionary *data = [serviceData objectAtIndex:i];
        NSString *uid = [data objectForKey:@"BrandID"];
        BrandData *localData = [BrandData getItemByID:uid];
        if (localData == nil) {
            localData = [[[BrandData alloc] init] autorelease];
        } else {
            //判断是否需要删除本地图片
            NSString *localUrl = localData.logo;
            NSString *serviceUrl = [data objectForKey:@"Logo"];
            if (![self checkImageUrlIsSame:localUrl serviceUrl:serviceUrl]) {
                [localData removeLogoImage];
            }
            NSString *localImages = localData.iPhoneImages;
            NSString *serviceImages = [data objectForKey:@"iPhoneImages"];
            if (![localImages isEqualToString:serviceImages]) {
                [localData removeAboutImages];
            }
        }
        //NSLog(@"save new data(%@)", localData);
        //添加，更新最新的数据
        [localData setValue:data];
        [localData save];
    }
    //取得最新的数据集
    NSArray *localDatas = [BrandData getAllItems];
    for (BrandData *data in localDatas) {
        NSString *localId = data.brandID;
        if ([self isNeedDeleteItem:localId serviceData:serviceData serviceKey:@"BrandID"]) {
            //NSLog(@"delete not exist data(%@)", data);
            [data removeLocalImages];
            [data deleteObject];
        }
    }
}

- (void) updateLocalStoreList:(NSArray *)serviceData {
    for (int i = 0; i < [serviceData count]; i++) {
        NSDictionary *data = [serviceData objectAtIndex:i];
        NSString *uid = [data objectForKey:@"StoreID"];
        StoreData *localData = [StoreData getItemByID:uid];
        if (localData == nil) {
            localData = [[[StoreData alloc] init] autorelease];
        }
        //NSLog(@"save new data(%@)", localData);
        //添加，更新最新的数据
        [localData setValue:data];
        [localData save];
    }
    //取得最新的数据集
    NSArray *localDatas = [StoreData getAllItems];
    for (StoreData *data in localDatas) {
        NSString *localId = data.storeID;
        if ([self isNeedDeleteItem:localId serviceData:serviceData serviceKey:@"StoreID"]) {
            //NSLog(@"delete not exist data(%@)", data);
            [data deleteObject];
        }
    }
}

- (void) updateLocalCityList:(NSArray *)serviceData {
    for (int i = 0; i < [serviceData count]; i++) {
        NSDictionary *data = [serviceData objectAtIndex:i];
        NSString *uid = [data objectForKey:@"CityID"];
        CityData *localData = [CityData getItemByID:uid];
        if (localData == nil) {
            localData = [[[CityData alloc] init] autorelease];
        }
        //NSLog(@"save new data(%@)", localData);
        //添加，更新最新的数据
        [localData setValue:data];
        [localData save];
    }
    //取得最新的数据集
    NSArray *localDatas = [CityData getAllItems];
    for (CityData *data in localDatas) {
        NSString *localId = data.cityID;
        if ([self isNeedDeleteItem:localId serviceData:serviceData serviceKey:@"CityID"]) {
            //NSLog(@"delete not exist data(%@)", data);
            [data deleteObject];
        }
    }
}

- (void)updateLocalProductList:(NSArray *)serviceData {
    for (int i = 0; i < [serviceData count]; i++) {
        NSDictionary *data = [serviceData objectAtIndex:i];
        NSString *uid = [data objectForKey:@"ProductID"];
        ProductData *localData = [ProductData getItemByID:uid];
        if (localData == nil) {
            localData = [[[ProductData alloc] init] autorelease];
        } else {
            //判断是否需要删除本地图片
            NSString *localImages = localData.iPhoneImages;
            NSString *serviceImages = [data objectForKey:@"iPhoneImages"];
            if (![localImages isEqualToString:serviceImages]) {
                [localData removeAllImages];
            }
        }
        //NSLog(@"save new data(%@)", localData);
        //添加，更新最新的数据
        [localData setValue:data];
        [localData save];
    }
    //取得最新的数据集
    NSArray *localDatas = [ProductData getAllItems];
    for (ProductData *data in localDatas) {
        NSString *localId = data.productID;
        if ([self isNeedDeleteItem:localId serviceData:serviceData serviceKey:@"ProductID"]) {
            //NSLog(@"delete not exist data(%@)", data);
            [data removeAllImages];
            [data deleteObject];
        }
    }
}

- (void)updateLocalAllShowList:(NSArray *)serviceData {
    for (int i = 0; i < [serviceData count]; i++) {
        NSDictionary *data = [serviceData objectAtIndex:i];
        NSString *uid = [data objectForKey:@"ShowID"];
        MyShowData *localData = [MyShowData getItemByID:uid];
        if (localData == nil) {
            localData = [[[MyShowData alloc] init] autorelease];
        } else {
            //判断是否需要删除本地图片
            NSString *localImages = localData.smallImage;
            NSString *serviceImages = [data objectForKey:@"SmallImage"];
            if (![localImages isEqualToString:serviceImages]) {
                [localData removeSmallImage];
            }
            
            localImages = localData.bigImage;
            serviceImages = [data objectForKey:@"BigImage"];
            if (![localImages isEqualToString:serviceImages]) {
                [localData removeBigImage];
            }
        }
        //NSLog(@"save new data(%@)", localData);
        //添加，更新最新的数据
        [localData setValue:data];
        [localData save];
    }
    //取得最新的数据集
    NSArray *localDatas = [MyShowData getAllItems];
    for (MyShowData *data in localDatas) {
        NSString *localId = data.showID;
        if ([self isNeedDeleteItem:localId serviceData:serviceData serviceKey:@"ShowID"]) {
            //NSLog(@"delete not exist data(%@)", data);
            [data removeBigImage];
            [data removeSmallImage];
        }
    }
}

- (void)syncRequestParseStatusNofity:(ParseData *)parseData {
    NSString *name = [self getRequestName:parseData.userInfo];
    NSLog(@"%@ Request finished！", name);
    int status = parseData.status;
    if (status == kParseDataFailed) {
        NSLog(@"%@ Request Failed! Reason:%@", name, parseData.error);
        finishedCount += BUFFER_IMAGE_COUNT;
    } else {
        NSArray *datas = [parseData.data objectForKey:@"items"];
        if ([@"NewsList" isEqualToString:name]) {
            [self updateLocalNewsList:datas];
        } else if ([@"VideoList" isEqualToString:name]) {
            [self updateLocalVideoList:datas];
        } else if ([@"BrandList" isEqualToString:name]) {
            [self updateLocalBrandList:datas];
        } else if ([@"StoreList" isEqualToString:name]) {
            [self updateLocalStoreList:datas];
        } else if ([@"CityList" isEqualToString:name]) {
            [self updateLocalCityList:datas];
        } else if ([@"ProductList" isEqualToString:name]) {
            [self updateLocalProductList:datas];
        } else if ([@"AllShowList" isEqualToString:name]) {
            [self updateLocalAllShowList:datas];
        }
        
    }
    finishedCount++;
    [self updateProgressView];
}

@end
